﻿#include "str.h"
#include <iostream>
#include <Windows.h>

std::wstring Utf8ToUtf16(const std::string& utf8)
{
	std::wstring utf16; // Result
	if (utf8.empty())
	{
		return utf16;
	}

	constexpr DWORD kFlags = MB_ERR_INVALID_CHARS;
	if (utf8.length() >= 1 << 16 )
	{
		throw std::overflow_error(
			"Input string too long: size_t-length doesn't fit into int.");
	}

	const int utf8Length = static_cast<int>(utf8.length());
	const int utf16Length = MultiByteToWideChar(CP_UTF8, kFlags, utf8.data(), utf8Length, nullptr, 0);

	utf16.resize(utf16Length);
	// Convert from UTF-8 to UTF-16
	int result = MultiByteToWideChar(CP_UTF8, kFlags, utf8.data(), utf8Length, &utf16[0], utf16Length);
	return utf16;
}
std::string Utf16ToUtf8(const std::wstring& utf16)
{
	std::string utf8; // Result
	if (utf16.empty())
	{
		return utf8;
	}


	if (utf16.length() >= 1 << 16)
	{
		throw std::overflow_error(
			"Input string too long: size_t-length doesn't fit into int.");
	}

	const int utf16Length = static_cast<int>(utf16.length());
	const int utf8Length = WideCharToMultiByte(CP_UTF8, 0, utf16.data(), -1, nullptr, 0, NULL, NULL);

	utf8.resize(utf8Length);
	// Convert from UTF-8 to UTF-16
	int result = WideCharToMultiByte(CP_UTF8, 0, utf16.data(), utf16Length, &(utf8[0]), utf8Length, NULL, NULL);
	return utf8;
}